<?php

namespace Largezhou\Admin\Traits;

use Closure;
use Largezhou\Admin\Components\Component;
use Largezhou\Admin\Components\Tools\ToolManager;

trait HeaderTools
{
    protected $toolsManager = null;
    protected $headerTools = [];

    /**
     * @return ToolManager
     */
    public function toolManager()
    {
        if ($this->toolsManager === null) {
            $this->toolsManager = new ToolManager();
        }

        return $this->toolsManager;
    }

    /**
     * 添加一个工具到顶部工具栏
     *
     * @param Component|Closure $tool 传入一个工具,或者传入一个会返回一个工具的回调函数
     * @param integer           $position 位置，默认是追加到最后
     */
    public function headerTool($tool, $position = null)
    {
        if ($position === null) {
            $position = count($this->headerTools);
        }

        array_splice($this->headerTools, $position, 0, [$tool]);
    }

    /**
     * @return array
     */
    public function headerTools()
    {
        return array_map(function ($tool) {
            return $tool instanceof Closure
                ? $tool($this->toolManager())
                : $tool;
        }, $this->headerTools);
    }
}
